package com.sds.session.service;

import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Session Client Service
 * @author dkg
 *
 */
@Service
public class UserSessionService {
	
	private Logger logger = LoggerFactory.getLogger(UserSessionService.class);
	private final String SP_DOMAIN = "http://localhost:8080/SpringWebProject";
	private final String IDP_DOMAIN = "http://localhost:8080/SpringWebProject";

	public void createSession(String userId, String userIP) throws Exception {
		logger.debug("################createSession################");
		logger.debug("User ID : " + userId);
		logger.debug("User IP : " + userIP);
		logger.debug("#############################################");
		
		URL url = new URL(IDP_DOMAIN + "/session/idp/createIDPSession.do");
		
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestMethod("POST");
		urlConn.setRequestProperty("userId", userId);
		urlConn.setRequestProperty("userIP", userIP);
		urlConn.setRequestProperty("domain", SP_DOMAIN);
		
		urlConn.getInputStream();
	}
	
	public boolean checkSession(String userId, String userIP) throws Exception {
		
		logger.debug("#################checkSession################");
		logger.debug("User ID : " + userId);
		logger.debug("User IP : " + userIP);
		logger.debug("#############################################");
		
		URL url = new URL(IDP_DOMAIN + "/session/idp/checkIDPSession.do");
		
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestMethod("POST");
		urlConn.setRequestProperty("userId", userId);
		urlConn.setRequestProperty("userIP", userIP);
		urlConn.setRequestProperty("domain", SP_DOMAIN);
		
		urlConn.getInputStream();
		if( "true".equals(urlConn.getHeaderField("CheckResult")) ) 
			return true;
		
		return false;
	}
	
}
